#include <config.h>
#include <stm32f0xx.h>
#include "device.h"
#include "stm32_key.h"

#ifdef USING_KEY

static struct key_device key_dev;

/*
 * keys
 */
typedef struct 
{
    uint32_t        clk;
    GPIO_TypeDef    *port;
    uint16_t        pin;
} per_key_t;

static per_key_t keys[] =
{
    {KEY1_CLK, KEY1_PORT, KEY1_PIN},
};

static bool is_key_press(uint8_t key_no)
{
    if (key_no >= array_size(keys)) return false;

    return !(keys[key_no].port->IDR & keys[key_no].pin);
}

static void setup_key_peri(per_key_t *key)
{
    GPIO_InitTypeDef GPIO_InitStructure;

    RCC_AHBPeriphClockCmd(key->clk, ENABLE);

    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
    GPIO_InitStructure.GPIO_Pin  = key->pin;
    GPIO_Init(key->port, &GPIO_InitStructure);
}

static const struct key_ops stm32_key_ops = 
{
    is_key_press,
};

void board_key_init(void)
{
    int i;

    for (i = 0; i < array_size(keys); i++)
    {
        setup_key_peri(&keys[i]);
        set_bit(key_dev.used, i);
    }

    key_dev.ops    = &stm32_key_ops;
    key_device_register(&key_dev, "key",
                        DEVICE_FLAG_INT_RX | DEVICE_FLAG_INT_TX,
                        NULL);
}

#endif
